﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.UserControls;
using Report.Model;

namespace Report.Forms
{
    public partial class FrmResultList1
    {
        private readonly ObservableCollection<FullData> _listLeft;
        private readonly ObservableCollection<FullData> _listRight;
        private readonly ReportManager2 _manager;
        private bool _orign;
        private FullData _data;
        private FrameworkElement _dragScope;
        private DragAdorner _adorner;
        private AdornerLayer _layer;

        public FrmResultList1()
        {
            InitializeComponent();
            Resources.MergedDictionaries.Add(ReportCommon.GetLan);
            _manager = ReportManager2.Create();
            _listLeft = new ObservableCollection<FullData>();
            _listRight = new ObservableCollection<FullData>();
            var temp = new List<FullData>();
            foreach (var sd in _manager.ResultInfo.Where(d => d.DataNo != 10034))
            {
                if (_manager.ResultSelected.Any(s => s.Id == sd.DataNo))
                {
                    temp.Add(sd);
                }
                else
                {
                    _listLeft.Add(sd);
                }
            }

            if (_manager.ResultSelected.Count != 0)
            {
                foreach (var sd in _manager.ResultSelected.OrderBy(d => d.Sequence))
                {
                    _listRight.Add(temp.Single(d => d.DataNo == sd.Id));
                }
            }
        }

        private void BtnOk_OnClick(object sender, RoutedEventArgs e)
        {
            if (_listRight.Count == 0) return;
            var sd = new List<SelectedData>();
            var index = 0;
            foreach (var fd in _listRight)
            {
                sd.Add(new SelectedData { Id = fd.DataNo, Sequence = index });
                index++;
            }

            var data = sd.First();
            data.Text = "";
            var sb = new StringBuilder();
            foreach (var control in SpStatItems.Children)
            {
                var cb = control as CheckBox;
                if (cb?.IsChecked != null && cb.IsChecked.Value)
                {
                    sb.Append(cb.Tag + ",");
                }
            }

            if (sb.Length > 0)
            {
                sb.Length--;
            }

            data.Text = sb.ToString();
            _manager.SetResultList(sd);
            DialogResult = true;
            Close();
        }

        private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void SelectedData_OnDrop(object sender, DragEventArgs e)
        {
            IDataObject da = e.Data;
            if (da.GetDataPresent(typeof(FullData)))
            {
                if (_orign)
                {
                    _listRight.Remove(_data);//添加
                    _listLeft.Add(_data);//删除
                }
                else
                {
                    _listLeft.Remove(_data);
                    _listLeft.Add(_data);
                }
            }

            ShowData.BorderBrush = Brushes.Gray;
            SData.BorderBrush = Brushes.Gray;
        }

        private void SelectedData_OnDragLeave(object sender, DragEventArgs e)
        {
            SData.BorderBrush = Brushes.Gray;
        }

        private void UIElement_OnPreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (sender is TextBlock textBlock)
            {
                int id = (int)textBlock.Tag;
                //startP = e.GetPosition(canvas1);
                //string name = (string)(sender as TextBlock).Name;
                //user = getUser(name);
                _data = _findData(id);
            }
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                _startMove((sender as TextBlock));
            }
        }

        private void _startMove(TextBlock t)
        {
            //实现拖拽的动画效果，画面不是很明显，要细看
            try
            {
                if (Application.Current.MainWindow != null)
                    _dragScope = Application.Current.MainWindow.Content as FrameworkElement;

                if (_dragScope != null)
                {
                    _dragScope.AllowDrop = true;
                    DragEventHandler draghandler = (DragScope_PreviewDragOver);
                    _dragScope.PreviewDragOver += draghandler;
                    _adorner = new DragAdorner(_dragScope, t, 0.5);
                    _layer = AdornerLayer.GetAdornerLayer(_dragScope);
                    _layer.Add(_adorner);
                    DataObject data = new DataObject(typeof(FullData), _data);
                    DragDrop.DoDragDrop(t, data, DragDropEffects.Move);
                    AdornerLayer.GetAdornerLayer(_dragScope).Remove(_adorner);
                    _adorner = null;
                    _dragScope.PreviewDragOver -= draghandler;
                }
            }
            catch
            {
                // ignored
            }
        }

        void DragScope_PreviewDragOver(object sender, DragEventArgs args)
        {
            if (_adorner != null)
            {
                _adorner.LeftOffset = args.GetPosition(_dragScope).X;
                _adorner.TopOffset = args.GetPosition(_dragScope).Y;
            }
        }

        private FullData _findData(int id)
        {
            //判断拖动源，来自_listLeft还是_listRight
            //Rectangle list1Rec = new Rectangle();
            if (ShowData.IsMouseCaptured)
            {
                ShowData.BorderBrush = Brushes.Coral;
                _orign = true;
                foreach (var u in _listRight)
                {
                    if (u.DataNo == id)
                        return u;
                }
            }

            else if (SData.IsMouseCaptured)//单击捕获
            {
                SData.BorderBrush = Brushes.Coral;
                _orign = false;//判断元素来源
                foreach (var usr in _listLeft)
                {
                    if (usr.DataNo == id)
                    {
                        return usr;
                    }
                }
            }

            return null;
        }

        private void Data_OnDragOver(object sender, DragEventArgs e)
        {
            if (!_orign)
                ShowData.BorderBrush = Brushes.Coral;
            else
                SData.BorderBrush = Brushes.Coral;

            if (!e.Data.GetDataPresent(typeof(FullData)))
            {
                e.Effects = DragDropEffects.None;//放置目标不接受该数据
                e.Handled = true;
            }
        }

        private void ShowData_OnDrop(object sender, DragEventArgs e)
        {
            IDataObject da = e.Data;
            if (da.GetDataPresent(typeof(FullData)))
            {
                if (_listRight.Count < 8)
                {
                    if (_orign)
                    {
                        _listRight.Remove(_data);
                        _listRight.Add(_data);
                    }
                    else
                    {
                        _listLeft.Remove(_data);
                        _listRight.Add(_data);
                    }
                }
            }

            ShowData.BorderBrush = Brushes.Gray;
            SData.BorderBrush = Brushes.Gray;
        }

        private void ShowData_OnDragLeave(object sender, DragEventArgs e)
        {
            ShowData.BorderBrush = Brushes.Gray;
        }

        private void FrmResultList1_OnLoaded(object sender, RoutedEventArgs e)
        {
            SData.ItemsSource = _listLeft;
            ShowData.ItemsSource = _listRight;
            var rs = _manager.ResultSelected.FirstOrDefault(d => !string.IsNullOrEmpty(d.Text));
            if (rs != null)
            {
                foreach (var str in rs.Text.Split(','))
                {
                    if (SpStatItems.FindName("Cb" + str) is CheckBox cb) cb.IsChecked = true;
                }
            }
        }

        private void BtnUp_OnClick(object sender, RoutedEventArgs e)
        {
            int i = ShowData.SelectedIndex;
            if (i <= 0)
            {
                return;
            }

            _listRight.Move(i, i - 1);
            ShowData.SelectedIndex = i - 1;
        }

        private void BtnDown_OnClick(object sender, RoutedEventArgs e)
        {
            int i = ShowData.SelectedIndex;
            if (i == -1 || i == ShowData.Items.Count - 1)
            {
                return;
            }

            _listRight.Move(i, i + 1);
            ShowData.SelectedIndex = i + 1;
        }

        private void Back_OnClick(object sender, RoutedEventArgs e)
        {
            if (!(ShowData.SelectedItem is FullData fd)) return;
            _listRight.Remove(fd);
            _listLeft.Add(fd);
        }

        private void Go_OnClick(object sender, RoutedEventArgs e)
        {
            if (!(SData.SelectedItem is FullData fd)) return;
            if (_listRight.Count >= 8) return;
            _listLeft.Remove(fd);
            _listRight.Add(fd);
        }

        private void BtnReset_OnClick(object sender, RoutedEventArgs e)
        {
            // _manager.SetDataList(null);
        }
    }
}
